﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using SQLServerHealthCheck.Model;
using System.Collections.ObjectModel;
using SQLServerHealthCheck.SQLServer;
using System.Threading;
using AG.Utilities;
using Microsoft.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;


namespace SQLServerOptimizer.PL.WPF
{
    public partial class TracingTemp : ResourceDictionary
    {
        HealthCheckDataContext dc;



        // DatabaseTrace databaseTrace;
        private T FindParent<T>(DependencyObject child)

        where T : DependencyObject
        {

            T parent = VisualTreeHelper.GetParent(child) as T;

            if (parent != null)

                return parent;

            else

                return FindParent<T>(parent);

        }

        public TracingTemp()
        {
            InitializeComponent();

        }

        private void combobox_tracing_intstance_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var combobox = sender as ComboBox;


            try
            {

                HealthCheckDataContext dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings.Get("ConnectionStringSSHCDatabase"));
                ComboBox _databasecombobox = (ComboBox)combobox.FindName("combobox_tracing_database");
                ComboBox _instancecombobox = (ComboBox)combobox.FindName("combobox_tracing_instance");

                Service instance = (_instancecombobox.SelectedItem as Service);

                if (instance != null)
                {
                    var qrydatabase = from db in dc.Databases
                                      where db.ServiceID == instance.ServiceID
                                      select db;

                    _databasecombobox.DisplayMemberPath = "DatabaseName";
                    _databasecombobox.ItemsSource = qrydatabase.ToList<Database>();
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
        private void combobox_tracing_database_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            try
            {

                var databaseComboBox = sender as ComboBox;
                System.Windows.Controls.Expander traceExpander = (System.Windows.Controls.Expander)databaseComboBox.FindName("Tracing_expander");
                if (traceExpander == null) return;

                System.Windows.Controls.ComboBox instanceComboBox = (System.Windows.Controls.ComboBox)traceExpander.FindName("combobox_tracing_instance");
                if (instanceComboBox == null) return;

                string tracingDatabaseName = string.Format("Server: {0}  Trace on database:" + " " + databaseComboBox.SelectedValue, instanceComboBox.SelectedValue);


                traceExpander.Header = tracingDatabaseName;





            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

        }
        private void btnScheduleTrace(object sender, RoutedEventArgs e)
        {
            var schedulebutton = sender as Button;
            try
            {


                //Get databaseTrace
                dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings.Get("ConnectionStringSSHCDatabase"));
                DatabaseTrace databaseTrace = (DatabaseTrace)schedulebutton.DataContext;
                int databaseTraceId = databaseTrace.DatabaseTraceId;
                //databaseTrace = dc.DatabaseTraces.FirstOrDefault(dt => dt.DatabaseTraceId == databaseTraceId);
                bool noproblems = true;
                if (databaseTraceId == 0)
                {

                    // schedule the trace
                    Application.Current.MainWindow.Cursor = Cursors.AppStarting;
                    System.Windows.Controls.ComboBox databaseComboBox = (System.Windows.Controls.ComboBox)schedulebutton.FindName("combobox_tracing_database");
                    if (databaseComboBox == null) return;
                    DatePicker startDate = (DatePicker)schedulebutton.FindName("calendar_Startdate");
                    if (startDate == null) return;
                    DatePicker EndDate = (DatePicker)schedulebutton.FindName("calendar_Enddate");
                    if (EndDate == null) return;

                    System.Windows.Controls.ComboBox starttime_hourComboBox = (System.Windows.Controls.ComboBox)schedulebutton.FindName("Time_StartTime_Hour");
                    if (starttime_hourComboBox == null) return;
                    System.Windows.Controls.ComboBox endtime_minComboBox = (System.Windows.Controls.ComboBox)schedulebutton.FindName("Time_StartTime_Min");
                    if (endtime_minComboBox == null) return;
                    System.Windows.Controls.ComboBox Time_EndTime_Hour = (System.Windows.Controls.ComboBox)schedulebutton.FindName("Time_EndTime_Hour");
                    if (Time_EndTime_Hour == null) return;
                    System.Windows.Controls.ComboBox Time_EndTime_Min = (System.Windows.Controls.ComboBox)schedulebutton.FindName("Time_EndTime_Min");
                    if (Time_EndTime_Min == null) return;
                    
                    DateTime start = new DateTime(startDate.SelectedDate.Value.Year, startDate.SelectedDate.Value.Month, startDate.SelectedDate.Value.Day, starttime_hourComboBox.SelectedIndex, endtime_minComboBox.SelectedIndex, 0);

                    if (start <= DateTime.Now)
                    {
                        noproblems = false;
                        MessageBox.Show("The start time must be after the current time " + DateTime.Now + ".", "Error Invalid Time.");

                    }


                    DateTime end = new DateTime(EndDate.SelectedDate.Value.Year, EndDate.SelectedDate.Value.Month, EndDate.SelectedDate.Value.Day, Time_EndTime_Hour.SelectedIndex, Time_EndTime_Min.SelectedIndex, 0);
                    if (end < DateTime.Now)
                    {
                        noproblems = false;
                        MessageBox.Show("The end time is invalid", "Error Invalid Time");

                    }
                    if (start > end  )
                    {
                        noproblems = false;
                        MessageBox.Show("The start time cannot be after end time", "Error Invalid Time");


                    }
                    if (noproblems)
                    {


                        Database database = (databaseComboBox.SelectedItem as Database);



                        databaseTrace.DatabaseTraceId = SQLServerHealthCheck.SQLServer.SQLTrace.ScheduleTrace(database, start, end);

                        DatabaseTrace newDatabaseTrace = dc.DatabaseTraces.FirstOrDefault(dt => dt.DatabaseTraceId == databaseTrace.DatabaseTraceId);
                        databaseTrace.TraceStart = newDatabaseTrace.TraceStart;
                        databaseTrace.TraceEnd = newDatabaseTrace.TraceEnd;
                        databaseTrace.Database = newDatabaseTrace.Database;






                        string imageUri = "pack://application:,,,/SQLServerOptimizer.PL.WPF;component/Images/tracerunning.png";
                        schedulebutton.IsEnabled = false;

                        schedulebutton.ToolTip = "Trace scheduled";

                        Image _imgrestor_down = (Image)schedulebutton.FindName("image_capturetrace");
                        if (_imgrestor_down == null) return;

                        _imgrestor_down.Source = new ImageSourceConverter().ConvertFromString(imageUri) as ImageSource;

                        Image _traceStatusIMG = (Image)schedulebutton.FindName("TraceStatusIMG");
                        _traceStatusIMG.Visibility = Visibility.Visible;
                        if (_traceStatusIMG == null) return;
                        _traceStatusIMG.Source = new ImageSourceConverter().ConvertFromString(imageUri) as ImageSource;

                        Label labelTracingUpdate = (Label)schedulebutton.FindName("traceProgressupdate");
                        if (labelTracingUpdate == null)
                            return;


                        labelTracingUpdate.Content = "Trace scheduled.";
                    }
                }

                else if (databaseTrace.State == DatabaseTraceState.Finished)
                {
                    schedulebutton.IsEnabled = true;
                    // CHeck if there are databaseTracedetails imported for this trace
                    int countDetails = dc.DatabaseTraceDetails.Count(dtd => dtd.DatabaseTraceId == databaseTraceId);

                    //If not  get the databasetrace details from the remote server.
                    // Then we can normalize the data.
                    if (countDetails == 0)
                    {
                        SQLTrace.ImportTraceDetailsfromServer(databaseTrace);
                        SQLTrace.NormalizeTextData(databaseTrace);
                    }

                    // Show the Tracing Reports.
                    //  TabControl mainTabControl = (TabControl)Application.Current.MainWindow.FindName("tabMain");

                    // mainTabControl.SelectedIndex = 4;

                    DatabaseTraceDetailsReportControl databaseTraceDetailsReport = (DatabaseTraceDetailsReportControl)Application.Current.MainWindow.FindName("DatabaseTraceDetails");

                    databaseTraceDetailsReport.DatabaseTraceID = databaseTrace.DatabaseTraceId;

                    databaseTraceDetailsReport.RefreshReport();
                    TabControl tabs = (TabControl)Application.Current.MainWindow.FindName("tabControl2");
                    tabs.SelectedIndex = 1;
                    //Get main window
                    //Select the Traeresult tab
                    //Set DatabaseTraceID property of control
                    //Call the RefreshReport

                }





            }

            catch (Exception ex)
            {
                Logger.Error(ex);
            }
            finally
            {

                Application.Current.MainWindow.Cursor = Cursors.Arrow;

            }

        }

        private childItem FindVisualChild<childItem>(DependencyObject obj)
               where childItem : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is childItem)
                    return (childItem)child;
                else
                {
                    childItem childOfChild = FindVisualChild<childItem>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }


    }
}
